import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:keyboard_avoider/keyboard_avoider.dart';
import 'package:dropdown_formfield/dropdown_formfield.dart';
import '../model.dart';
import 'model.dart';
import 'property_log.dart';

var gItem = {
  'id': '',
  'account_type': '1',
  'account_name': '',
  'money': '',
  'due_date': '',
  'is_statistic': '1'
};

class PropertyDetail extends StatelessWidget {
  final Post item;
  const PropertyDetail({Key key, this.item}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    if (item != null) {
      gItem['account_type'] = item.account_type;
      gItem['account_name'] = item.account_name;
      gItem['money'] = item.money;
      gItem['due_date'] = item.due_date == '0000-00-00' ? '无' : item.due_date;
      gItem['is_statistic'] = item.is_statistic;
      gItem['id'] = item.id;
    }
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(gItem['id'] == '' ? '添加账户' : '编辑账户'),
        elevation: 0.0,
      ),
      body: Theme(
        data: Theme.of(context).copyWith(
          primaryColor: Colors.black,
        ),
        child:
            Container(padding: EdgeInsets.all(16.0), child: AddPropertyForm()),
      ),
    );
  }
}

class AddPropertyForm extends StatefulWidget {
  @override
  AddPropertyFormState createState() => AddPropertyFormState();
}

class AddPropertyFormState extends State<AddPropertyForm> {
  // TextEditingController selectionController = TextEditingController();
  // FocusNode textFieldFocusNode = FocusNode();
  DateTime selectedDate = DateTime.now();
  final propertyFormKey = GlobalKey<FormState>();
  String account_type = gItem['account_type'],
      account_name = gItem['account_name'],
      money = gItem['money'],
      due_date = gItem['due_date'];
  String is_statistic = gItem['is_statistic'];
  bool autovalidate = false;

  void _submitPropertyForm() {
    if (propertyFormKey.currentState.validate()) {
      propertyFormKey.currentState.save();
      this.fetchPosts(
          account_type, account_name, money, due_date, is_statistic);
      EasyLoading.show(
          status: 'loading...', maskType: EasyLoadingMaskType.black);
    } else {
      setState(() {
        autovalidate = true;
      });
    }
  }

  String validateWebsite(value) {
    if (value.isEmpty) {
      return '网站名是必填项！';
    }
    return null;
  }

  String validateUsername(value) {
    if (value.isEmpty) {
      return '用户名是必填项！';
    }
    return null;
  }

  _openAlertDialog(id) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('删除'),
          content: Text('确定要删除该条数据吗?'),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            ElevatedButton(
              style: ButtonStyle(
                backgroundColor:
                    MaterialStateProperty.all(Color(0xfff44336)), //背景颜色
              ),
              child: Text('确定'),
              onPressed: () {
                _deleteProperty(id);
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  Future _deleteProperty(id) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print('prefs');
    // 获得密码
    final response = await http.get(
      'https://me.yuanqiao.pw/api/me/deleteProperty.php?id=' + id,
      headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')},
    );
    print('response');
    print(response);
    if (response.statusCode == 200) {
      final responseBody = json.decode(response.body);
      Fluttertoast.showToast(
          msg: responseBody['error'],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
      if (responseBody['state'] == '1') {
        Navigator.of(context).pushNamed('/home', arguments: ScreenArguments(2));
      }
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }

  Future<void> _selectDate(BuildContext context) async {
    //初始化日期选择控件
    final DateTime picked = await showDatePicker(
        context: context,
        initialDate: selectedDate, //默认日期
        firstDate: DateTime(2015, 8), //起始日期
        lastDate: DateTime(2101)); //最大日期
    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked; //改变选择的日期值
        due_date = "${picked.toLocal()}".split(' ')[0];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardAvoider(
        autoScroll: true,
        child: Form(
            key: propertyFormKey,
            child: SingleChildScrollView(
                child: Column(
              children: <Widget>[
                Container(
                  child: DropDownFormField(
                    titleText: '账户类型',
                    hintText: '请选择账户类型',
                    value: account_type,
                    onSaved: (value) {
                      setState(() {
                        account_type = value;
                      });
                    },
                    onChanged: (value) {
                      setState(() {
                        account_type = value;
                      });
                    },
                    dataSource: [
                      {
                        "display": "资金账户",
                        "value": "1",
                      },
                      {
                        "display": "虚拟账户",
                        "value": "2",
                      },
                      {
                        "display": "借入借出",
                        "value": "3",
                      },
                    ],
                    textField: 'display',
                    valueField: 'value',
                  ),
                ),
                TextFormField(
                    initialValue: account_name,
                    decoration: InputDecoration(
                      labelText: '账户名称',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      account_name = value;
                    }),
                TextFormField(
                    keyboardType: TextInputType.number,
                    initialValue: money,
                    decoration: InputDecoration(
                      labelText: '金额',
                      helperText: '',
                    ),
                    onSaved: (value) {
                      money = value;
                    },
                    validator: validateUsername),
                Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text('到期时间：' + (due_date == '' ? '无' : due_date)),
                      ElevatedButton(
                          child: Text('选择日期'),
                          onPressed: () => {_selectDate(context)})
                    ]),
                // 带标题的选中框
                CheckboxListTile(
                  value: this.is_statistic == '0' ? false : true,
                  // 改变后的事件
                  onChanged: (value) {
                    setState(() {
                      this.is_statistic = value == true ? '1' : '0';
                    });
                  },
                  title: Text("是否计入资产"),
                ),
                SizedBox(
                  height: 32.0,
                ),
                Container(
                  width: double.infinity,
                  child: ElevatedButton(
                    style: ButtonStyle(
                        // foregroundColor: Theme.of(context).accentColor, //字体颜色
                        elevation: MaterialStateProperty.all(0)),
                    child: Text('提交', style: TextStyle(color: Colors.white)),
                    onPressed: _submitPropertyForm,
                  ),
                ),
                (gItem['id'] != ''
                    ? Container(
                        width: double.infinity,
                        child: ElevatedButton(
                          style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.all(
                                  Color(0xfff44336)), //背景颜色
                              // foregroundColor: Theme.of(context).accentColor, //字体颜色
                              elevation: MaterialStateProperty.all(0)),
                          child:
                              Text('删除', style: TextStyle(color: Colors.white)),
                          onPressed: () => this._openAlertDialog(gItem['id']),
                        ),
                      )
                    : Container()),
                gItem['id'] != '' ? PropertyLog(id: gItem['id']) : Container()
              ],
            ))));
  }

  Future fetchPosts(
      $account_type, $account_name, $money, $due_date, $is_statistic) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dataBody = jsonEncode({
      'id': gItem['id'] != '' ? gItem['id'] : '',
      'account_type': $account_type,
      'account_name': $account_name,
      'money': $money,
      'old_money': gItem['money'],
      'due_date': $due_date,
      'is_statistic': $is_statistic == '0' ? false : true
    });
    print(dataBody);
    final response = await http.post(
        'https://me.yuanqiao.pw/api/me/editProperty.php',
        body: dataBody,
        headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')});
    EasyLoading.dismiss();
    final responseBody = json.decode(response.body);
    print('responseBody');
    print(responseBody);
    print(response.statusCode);
    print(response.body);

    if (response.statusCode == 200) {
      gItem['id'] = '';
      gItem['account_type'] = '1';
      gItem['account_name'] = '';
      gItem['money'] = '';
      gItem['due_date'] = '';
      gItem['is_statistic'] = '1';
      final responseBody = json.decode(response.body);
      print('responseBody');
      print(responseBody);
      Fluttertoast.showToast(
          msg: responseBody['error'],
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
      Navigator.of(context).pushNamed('/home', arguments: ScreenArguments(2));
    } else {
      Fluttertoast.showToast(
          msg: '网络或服务器错误',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.white,
          textColor: Colors.black87,
          fontSize: 16.0);
    }
  }
}
